<template>
    <div class="app-container">
      <el-button type="primary" @click="popup_edit(0)">新增角色</el-button>
      <el-table :data="rolesList" class="mt30 width100" border>
        <el-table-column align="center" label="编号" width="50">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="角色类型" width="150">
          <template slot-scope="scope">
            {{ scope.row.role_type_name }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="角色名称" width="220">
          <template slot-scope="scope">
            {{ scope.row.role_name }}
          </template>
        </el-table-column>
        <el-table-column align="header-center" label="说明">
          <template slot-scope="scope">
            {{ scope.row.about }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="popup_edit(scope.row.id)">编辑权限</el-button>
            <el-button type="danger" size="small" @click="popup_delete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="result.total>0" :total="result.total" :page.sync="formdata.pageindex" :limit.sync="formdata.pagesize" @pagination="getRoles" />
      <el-dialog
        v-if="tmp.dialogType=='edit'&&tmp.dialogFormVisible"
        class="aboutDialog"
        :close-on-click-modal="false"
        title="编辑"
        :visible.sync="tmp.dialogFormVisible"
      >
        <edit ref="edit" :detail-id="tmp.detailId" @dialogClose="dialogClose" />
      </el-dialog>
    </div>
  </template>
  
  <script>
//   import path from 'path'
//   import { deepClone } from '@/utils'
//   import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
import Pagination from '@/components/Pagination/index' // 分页secondary package based on el-pagination
import edit from './role-edit'
  const defaultRole = {
    key: '',
    name: '',
    description: '',
    routes: []
  }
  
  export default {
    components: {
        Pagination,
        edit,
  },
    data() {
      return {
        role: Object.assign({}, defaultRole),
        routes: [],
        rolesList: [],
        dialogVisible: false,
        dialogType: 'new',
        checkStrictly: false,
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        formdata: {
            pageindex: 1,
            pagesize: 20,
        },
        result: {
            total: 0,
            rows: []
        },
        tmp: {
            detailId: 0,
            dialogType: '',
            dialogFormVisible: false // 控制弹窗显示隐藏的值
      },
        }
    },
    computed: {
      routesData() {
        return this.routes
      }
    },
    created() {
      // Mock: get all routes and roles list from server
    //   this.getRoutes()
      this.getRoles()
    },
    methods: {
      async getRoutes() {
        const res = await getRoutes()
        this.serviceRoutes = res.data
        this.routes = this.generateRoutes(res.data)
      },
      getRoles() {
        this.$api.auth.auth_menurolelist(this.formdata).then(response => {
            this.rolesList = response.data.rows
            this.result = response.data
            this.deal_data()
      })
      },
      deal_data() {

      },
      // Reshape the routes structure so that it looks the same as the sidebar
      generateRoutes(routes, basePath = '/') {
        const res = []
  
        for (let route of routes) {
          // skip some route
          if (route.hidden) { continue }
  
          const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)
  
          if (route.children && onlyOneShowingChild && !route.alwaysShow) {
            route = onlyOneShowingChild
          }
  
          const data = {
            path: path.resolve(basePath, route.path),
            title: route.meta && route.meta.title
  
          }
  
          // recursive child routes
          if (route.children) {
            data.children = this.generateRoutes(route.children, data.path)
          }
          res.push(data)
        }
        return res
      },
      generateArr(routes) {
        let data = []
        routes.forEach(route => {
          data.push(route)
          if (route.children) {
            const temp = this.generateArr(route.children)
            if (temp.length > 0) {
              data = [...data, ...temp]
            }
          }
        })
        return data
      },
      //* *****************  基础业务  **************************
      popup_edit(id) {
        this.tmp.dialogType = 'edit'
        this.tmp.detailId = id
        this.tmp.dialogFormVisible = true
      },
      popup_delete({ $index, row }) {
        this.$confirm('确定要删除此角色吗？删除后不可恢复！', '警告', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            this.delete(id)
            // await deleteRole(row.key)
            // this.rolesList.splice($index, 1)
            // this.$message({
            //   type: 'success',
            //   message: 'Delete succed!'
            // })
          })
          .catch(err => { console.error(err) })
      },
      delete(id) {
      this.$api.user.auth_menuroledelete({ id: id }).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        // this.load_data()
      })
    },
    dialogClose() {
      this.resetTemp()
      this.tmp.dialogFormVisible = false
    //   this.load_data()
    },
      generateTree(routes, basePath = '/', checkedKeys) {
        const res = []
  
        for (const route of routes) {
          const routePath = path.resolve(basePath, route.path)
  
          // recursive child routes
          if (route.children) {
            route.children = this.generateTree(route.children, routePath, checkedKeys)
          }
  
          if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
            res.push(route)
          }
        }
        return res
      },
    //   async confirmRole() {
    //     const isEdit = this.dialogType === 'edit'
  
    //     const checkedKeys = this.$refs.tree.getCheckedKeys()
    //     this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)
  
    //     if (isEdit) {
    //       await updateRole(this.role.key, this.role)
    //       for (let index = 0; index < this.rolesList.length; index++) {
    //         if (this.rolesList[index].key === this.role.key) {
    //           this.rolesList.splice(index, 1, Object.assign({}, this.role))
    //           break
    //         }
    //       }
    //     } else {
    //       const { data } = await addRole(this.role)
    //       this.role.key = data.key
    //       this.rolesList.push(this.role)
    //     }
  
    //     const { description, key, name } = this.role
    //     this.dialogVisible = false
    //     this.$notify({
    //       title: 'Success',
    //       dangerouslyUseHTMLString: true,
    //       message: `
    //           <div>Role Key: ${key}</div>
    //           <div>Role Name: ${name}</div>
    //           <div>Description: ${description}</div>
    //         `,
    //       type: 'success'
    //     })
    //   },
      // reference: src/view/layout/components/Sidebar/SidebarItem.vue
      onlyOneShowingChild(children = [], parent) {
        let onlyOneChild = null
        const showingChildren = children.filter(item => !item.hidden)
  
        // When there is only one child route, the child route is displayed by default
        if (showingChildren.length === 1) {
          onlyOneChild = showingChildren[0]
          onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
          return onlyOneChild
        }
  
        // Show parent if there are no child route to display
        if (showingChildren.length === 0) {
          onlyOneChild = { ... parent, path: '', noShowingChildren: true }
          return onlyOneChild
        }
  
        return false
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .app-container {
    .roles-table {
      margin-top: 30px;
    }
    .permission-tree {
      margin-bottom: 30px;
    }
  }
  </style>
  